#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>

#define LOG_TAG    "tcp_server"
#define LOG_LVL    ELOG_LVL_VERBOSE
#include <elog.h>

#define     LOG_D       log_d
#define     LOG_I       log_i
#define     LOG_W       log_w
#define     LOG_E       log_e

void tcp_server(void)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        LOG_E("socket create failed");
        return;
    }

    int opt = 1;
    setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    
    struct sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(12800);

    int err = bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
    if (err < 0) {
        LOG_E("socket bind failed");
        close(sockfd);
        return;
    }

    err = listen(sockfd, 5);
    if (err < 0) {
        LOG_E("socket listen failed");
        close(sockfd);
        return;
    }
    int keepAlive = 1;
    int keepIdle = 5;
    int keepInterval = 5;
    int keepCount = 3;
    char addr_str[128] = {0};

    while (1) {
        struct sockaddr_in client_addr;
        socklen_t client_addr_len = sizeof(client_addr);
        int client_sockfd = accept(sockfd, (struct sockaddr *)&client_addr, &client_addr_len);
        if (client_sockfd < 0) {
            LOG_E("socket accept failed");
            break;
        }

        setsockopt(client_sockfd, SOL_SOCKET, SO_KEEPALIVE, &keepAlive, sizeof(int));
        setsockopt(client_sockfd, IPPROTO_TCP, TCP_KEEPIDLE, &keepIdle, sizeof(int));
        setsockopt(client_sockfd, IPPROTO_TCP, TCP_KEEPINTVL, &keepInterval, sizeof(int));
        setsockopt(client_sockfd, IPPROTO_TCP, TCP_KEEPCNT, &keepCount, sizeof(int));

        // 将网络字节序的 IP 地址转换为主机字节序的可读字符串
        inet_ntop(AF_INET, &(client_addr.sin_addr), addr_str, INET_ADDRSTRLEN);
        // 将网络字节序的端口号转换为主机字节序
        uint16_t port = ntohs(client_addr.sin_port);

        LOG_D("Socket accepted ip address: %s:%d", addr_str, port);

        // 处理客户端连接
        int len;
        char *buffer = NULL;

        buffer = malloc(2048);
        if (buffer == NULL) {
            LOG_E("malloc failed");
            goto __err_exit;
        }
        memset(buffer, 0, 2048);

        do {
            len = recv(client_sockfd, buffer, 2048, 0);
            if (len > 0) {
                // 处理接收到的数据
                LOG_D("Received data: %s", buffer);
            } else if (len == 0) {
                // 客户端断开连接
                LOG_D("Client disconnected");
                break;
            } else {
                // 处理接收错误
                LOG_E("recv failed");
                break;
            }

            int to_write = len;
            while (to_write > 0) {
                int bytes_written = send(client_sockfd, buffer + len - to_write, to_write, 0);
                if (bytes_written <= 0) {
                    LOG_E("send failed");
                    goto __err_exit;
                }
                to_write -= bytes_written;
            }
        } while (len > 0);

__err_exit:
        if (buffer) {
            free(buffer);
            buffer = NULL;
        }
        
        shutdown(client_sockfd, 0);
        close(client_sockfd);
    }
    close(sockfd);
}